from django.http import HttpResponse, HttpResponseRedirect

from django.contrib.auth.forms import UserCreationForm
from django import forms

from django.template import RequestContext
from django.shortcuts import render_to_response

from MacGyver.cookbook.models import Recipie, RecipieSearchForm, Item

def index(request):
	return render_to_response('basic/index.html', context_instance=RequestContext(request))

def about(request):
	return render_to_response('basic/about.html', context_instance=RequestContext(request))

def register(request):
    if request.method == 'POST':
        form = UserCreationForm(request.POST)
        if form.is_valid():
            new_user = form.save()
            return HttpResponseRedirect("/account")
    else:
        form = UserCreationForm()
    return render_to_response("registration/register.html", {
        'form': form,
    } , context_instance=RequestContext(request))

def recipie(request):
	recipies = Recipie.objects.all()
	return render_to_response('basic/recipie_list.html',
            {'recipies': recipies,}, context_instance=RequestContext(request))
     
def recipie_details(request, recipie_id):
	recipie = Recipie.objects.get(id = recipie_id)
	return render_to_response('basic/recipie_details.html',
            {'recipie': recipie,}, context_instance=RequestContext(request))   

def voting(request):
	pass

def search_recipie(request):
	if request.method == 'GET':
		form = RecipieSearchForm(request.GET) 
		if form.is_valid():
			
			recipieList = []
			idsInt = []
	
			for ID in map(int, request.GET.getlist('items')):
				item_list = Item.objects.all()
				all_recipies = Recipie.objects.all()

				for recept in all_recipies:
					match = True
					for item in recept.items.all():
						if idsInt.count(item.id) == 0 : match = False
					if match: recipieList.append(recept)

			print recipieList
			return render_to_response('basic/search_results.html', {'recipies': recipieList } ,context_instance=RequestContext(request) )
	else:
		form = RecipieSearchForm()
	
	return render_to_response('basic/search_recipie.html', {
        'form': form,
    },  context_instance=RequestContext(request))


